package ru.pb.game.network.engine.client.packets.receivable;

import ru.pb.game.network.engine.client.packets.FromClientToGameServerPacket;
import ru.pb.game.network.engine.client.packets.sendable.PROTOCOL_BATTLE_READYBATTLE_ACK;
import ru.pb.game.objects.model.players.Player;
import ru.pb.game.objects.model.players.enums.SLOT_STATE;
import ru.pb.game.objects.model.room.Room;
import ru.pb.game.objects.storage.ObjectsStorage;

public class PROTOCOL_BATTLE_READYBATTLE_REQ extends FromClientToGameServerPacket
{
	// private int _frost, _count;
	// private String _str;

	@Override
	public void readImpl()
	{
		readH();
		// _frost = readH();
		// _count = readC();
		// _str = readS(_count);

	}

	@Override
	public void runImpl()
	{
		Player p = getPlayer();
		if(p.getRoom() != null)
		{
			Room room = p.getRoom();
			Player leader = room.getLeader();

			if(p != null && room != null)
			{
				if(leader.equals(p))
				{
					room.setInFight(true);
					Player member = null;
					for(int objId : room.getAllPlayers().toArray())
					{
						member = ObjectsStorage.getInstance().getPlayer(objId);
						if(room.getSlotState(member.getSlot()) == SLOT_STATE.SLOT_STATE_READY && !leader.equals(member))
						{
							member.sendPacket(new PROTOCOL_BATTLE_READYBATTLE_ACK(p));
							room.changeSlotState(member.getSlot(), SLOT_STATE.SLOT_STATE_PRESTART);
						}
						else if(room.getLeader().equals(member))
						{
							member.sendPacket(new PROTOCOL_BATTLE_READYBATTLE_ACK(member));
							room.changeSlotState(member.getSlot(), SLOT_STATE.SLOT_STATE_PRESTART);
						}
					}
				}
				else
				{
					if(room.getSlotState(leader.getSlot()) == SLOT_STATE.SLOT_STATE_PRESTART || room.getSlotState(leader.getSlot()) == SLOT_STATE.SLOT_STATE_BATTLE)
					{
						room.changeSlotState(p.getSlot(), SLOT_STATE.SLOT_STATE_PRESTART);
						p.sendPacket(new PROTOCOL_BATTLE_READYBATTLE_ACK(p));
					}

					if(room.getSlotState(p.getSlot()) == SLOT_STATE.SLOT_STATE_READY)
					{
						room.changeSlotState(p.getSlot(), SLOT_STATE.SLOT_STATE_NORMAL);
					}
					else if(room.getSlotState(p.getSlot()) == SLOT_STATE.SLOT_STATE_NORMAL)
					{
						room.changeSlotState(p.getSlot(), SLOT_STATE.SLOT_STATE_READY);
					}
				}
				p.getRoom().updateInfo();
			}
		}
	}
}